package com.cdsxt.exception.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cdsxt.util.JsonUtil;
import com.cdsxt.util.ThrowableUtil;
import com.cdsxt.vo.ResponseResultVo;

@ControllerAdvice
public class GlobalExceptionHandler {

	//TODO 使用日志记录器记录错误信息
	
	/**
	 * 统一异常处理器：处理器
	 */
	@ExceptionHandler(value=Exception.class)
	@ResponseBody
	public void exceptionHandler(HttpServletRequest req,HttpServletResponse resp, Exception e)throws Exception{
		//日志记录
		e.printStackTrace(System.out);
		//转换信息
		/**
		 * 开发的时候使用
		 * ThrowableUtil.throwableToString(e);
		 * 正式环境改为：服务器忙，请稍后再尝试
		 */
		String errorMsg=ThrowableUtil.throwableToString(e);
		
		//判断ajax请求
		String requestType = req.getHeader("X-Requested-With");
		if("XMLHttpRequest".equals(requestType)){
			//AJAX请求
			//写json字符串给用户信息
			ResponseResultVo errorVo = ResponseResultVo.errorResult(errorMsg);
			String jsonStr=JsonUtil.objToJsonStr(errorVo);
			resp.setContentType("application/json;charset=utf-8");
			resp.getWriter().println(jsonStr);
		}else{
			
			//非AJAX请求
			req.setAttribute("errorMsg", errorMsg);
		    req.getRequestDispatcher("/views/common/error.jsp").forward(req, resp);
		} 
	}
}
